package com.lagou.handler;

import com.lagou.protocol.RpcRequest;
import com.lagou.service.UserServiceImpl;
import com.lagou.util.SpringBeanUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.lang.reflect.Method;

public class UserServerHandler extends ChannelInboundHandlerAdapter {


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        try {
            // 获取class
            RpcRequest rpcRequest = (RpcRequest) msg;
            String className = rpcRequest.getClassName();
            Class<?> aClass = Class.forName(className);

            // 获取bean对象
            Object bean = SpringBeanUtil.getBean(aClass);

            // 获取要执行的方法
            String methodName = rpcRequest.getMethodName();
            Class<?>[] parameterTypes = rpcRequest.getParameterTypes();
            Method method = aClass.getDeclaredMethod(methodName, parameterTypes);

            // 执行方法
            Object result = method.invoke(bean, rpcRequest.getParameters());
            ctx.writeAndFlush(result.toString() + "--> success");
        } catch (Exception e) {
            e.printStackTrace();
            ctx.writeAndFlush(e.getMessage() + "--> fail");
        }
    }
}
